from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from user import models
from utils.jwttool import tooljwt
import jwt


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION', '')
        if not token:
            raise AuthenticationFailed("请先登录并且设置token")
        try:
            retoken = token.split(" ")[1]
            payload = tooljwt.checkToken(retoken)
            user = models.UserModel.objects.get(id=payload['userid'])
            return user, payload
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed("token过期")
        except jwt.InvalidTokenError:
            raise AuthenticationFailed("token无效")
